package com.example.addviewdemo;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private LinearLayout llContent;
    private TextView textView, tvDynamic, tvRemove;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListener();
    }

    /**
     * 初始化view
     */
    private void initView() {
        llContent = findViewById(R.id.content);
        textView = findViewById(R.id.tv_add);
        tvDynamic = findViewById(R.id.tv_dynamic_add);
        tvRemove = findViewById(R.id.tv_remove);
    }

    /**
     * 初始化事件监听
     */
    private void initListener() {
        //添加一个文字
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addView(v);
            }
        });
        //动态添加商品
        tvDynamic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addSpec();
            }
        });
        //移除
        tvRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //根据view的数量移除最后一个
                View view = llContent.getChildAt(llContent.getChildCount() - 1);
                llContent.removeView(view);
            }
        });
    }

    /**
     * 按钮点击事件，向容器中添加TextView
     * @param view
     */
    public void addView(View view) {
        TextView child = new TextView(this);
        child.setTextSize(20);
        child.setTextColor(getResources().getColor(R.color.colorAccent));
        child.setText("找到很多女朋友");
        // 调用一个参数的addView方法
        llContent.addView(child);
    }

    /**
     * 添加一个商品规格
     */
    private void addSpec() {
        View view1 = LayoutInflater.from(this).inflate(R.layout.layout_item_standard, null);
        llContent.addView(view1);
    }
}
